package com.xie.smfs.util;

import net.fabricmc.fabric.api.event.player.PlayerBlockBreakEvents;
import net.fabricmc.fabric.api.event.player.UseBlockCallback;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.util.ActionResult;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class PlayerBlockActionTracker {
    private static final Map<UUID, Long> lastBlockActionTime = new HashMap<>();

    public static void registerEvents() {
        // 监听方块破坏事件
        PlayerBlockBreakEvents.AFTER.register((world, player, pos, state, blockEntity) -> {
            if (player instanceof ServerPlayerEntity) {
                recordBlockAction(player.getUuid());
            }
        });

        // 监听方块放置事件
        UseBlockCallback.EVENT.register((player, world, hand, hitResult) -> {
            if (player instanceof ServerPlayerEntity && hand == net.minecraft.util.Hand.MAIN_HAND) {
                recordBlockAction(player.getUuid());
            }
            return ActionResult.PASS;
        });
    }

    private static void recordBlockAction(UUID playerUuid) {
        lastBlockActionTime.put(playerUuid, System.currentTimeMillis());
    }

    public static boolean hasRecentBlockAction(UUID playerUuid, int ticks) {
        long currentTime = System.currentTimeMillis();
        long actionTime = lastBlockActionTime.getOrDefault(playerUuid, 0L);
        // 将游戏刻转换为毫秒 (1刻 = ~50ms)
        return currentTime - actionTime < ticks * 50;
    }
}